package com.sgb.kjwl.viewmodel.home;

import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.jicai.entity.CentralizedMiningEntity;
import com.sgb.jicai.entity.FactoryCentralizedListEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.jicai.entity.FactoryCentralizedItemEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.home.CentralizedMiningFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

public class CentralizedMininglModel extends BaseViewModel {
    public HomeRepertory repertory;
    private CentralizedMiningFragment fragment;
    private int page = 1;
    private Map map;
    private List<PickSelectEntity> typeEntityList = new ArrayList<>();

    public CentralizedMininglModel(CentralizedMiningFragment fragment, HomeRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
    }

    public void getJiCaiList(int groupBuyType, boolean b, int groupClass, int page, boolean isRefresh, String typeNo) {
        map = new HashMap();
        map.put("limit", 3);
        map.put("current", page);
        map.put("status", "1");   //1为集采中
        if (groupBuyType == 3) {//为企业专项类型,企业专项穿下面字段
            map.put("groupbuyClass", groupClass == 0 ? "" : groupClass);//集采类型  商品、机械、设备…………
            map.put("groupBuyMode", "2");//为2时企业专项数据
        } else {//需方发起数据  穿下面字段
            map.put("groupBuyMode", "1");//需方发起数据。为2时企业专项数据
            if (groupBuyType > 0) {
                map.put("groupBuyType", groupBuyType);//集采方式  0  全部   1.即报即采  2.汇集采购  3.企业专项
            }
            map.put("groupbuyClass", groupClass == 0 ? "" : groupClass);//集采类型  商品、机械、设备…………
            map.put("typeNo", typeNo);
        }
        if (fragment.getPosition() == 0 && page == 1 && groupClass == 1 && groupBuyType == 1) {
            Type type = new TypeToken<ListResponse<List<CentralizedMiningEntity>>>() {
            }.getType();
            Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.GroupBuyClass + groupBuyType, type);
            if (null != obj && !isRefresh) {
                ListResponse<List<CentralizedMiningEntity>> dataList = (ListResponse<List<CentralizedMiningEntity>>) obj;
                fragment.showList(dataList.getList(), b);
                return;
            }
        }
        DialogHelper.showProgressDialog(fragment.getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getCentralizedMiningAPI().getJiCaiList(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<CentralizedMiningEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<CentralizedMiningEntity>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data == null || data.getState() == null) {
                    fragment.showList(null, false);
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (fragment.getPosition() == 0 && page == 1) {
                        String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                        String CacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.GroupBuyClass + groupBuyType);
                        if (!mHashNet.equals(CacheOperationHash)) {
                            fragment.showList(data.getData().getList(), b);
                            DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.GroupBuyClass + groupBuyType, data.getData());
                        } else {
                            fragment.showList(data.getData().getList(), b);
                        }
                    } else {
                        fragment.showList(data.getData().getList(), b);
                    }
                } else {
                    fragment.showList(null, false);
                }
            }
        });
    }

    //    public void recomandCate(String code) {
//        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
//        APIManager.getInstance().getBigHomeAPI().recomandCate(repertory.getAreaCode(),code).enqueue(new Callback<BaseEntity<BigHomeAndroidEntity>>() {
//            @Override
//            public void onResponse(Call<BaseEntity<BigHomeAndroidEntity>> call, Response<BaseEntity<BigHomeAndroidEntity>> response) {
//                DialogHelper.dismissProgressDialog();
//                if (data == null) {
//                    return;
//                }
//                if (data.getState().equals(APIManager.RESPONSE_OK)) {
//                    if (code.equals("groupbuy")) {
//                        fragment.showOption1View(data.getData());
//                    } else {
//                        MToast.showToast(fragment.getActivity(), response.message());
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(Call<BaseEntity<BigHomeAndroidEntity>> call, Throwable t) {
//                DialogHelper.dismissProgressDialog();
//                MToast.showToast(fragment.getActivity(), t.getMessage());
//            }
//        });
//    }
    public void getH5Url(String id, String tag) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(tag).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {//type 0 首页 1 我的集采 2 我的报价
                    SharedPreferenceUtil.init(fragment.getActivity());
                    String token = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.resourceAPPToken, "");
                    String url = data.getData().getUrl() + "?id=" + id + "&type=0" + "&token=" + repertory.getToken();
//                    String url = "http://192.168.2.33:8067/collection" + "?id=" + id + "&type=0"+"&token="+ repertory.getToken();
                    WebViewX5HostActivity.start(fragment.getActivity(), url);
                } else {
                    MToast.showToast(fragment.getContext(), data.getMsg());
                }
            }
        });
    }

    /**
     * 获取集采数据标题菜单
     */
    public void groupBuyClassList(int mItemType) {
        if (mItemType == 4) {   //供方发起
            getTenderCategoryAllList();
        } else {
            Type type = new TypeToken<List<PickSelectEntity>>() {
            }.getType();
            Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.GroupBuyClass, type);
            if (null != obj) {
                List<PickSelectEntity> dataList = (List<PickSelectEntity>) obj;
                fragment.showOption1View2(dataList);
            }
            DialogHelper.showProgressDialog(fragment.getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
            APIManager.getInstance().getCentralizedMiningAPI().groupBuyClassList().enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
                @Override
                public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                    DialogHelper.dismissProgressDialog();
                    if (data.getState().equals(APIManager.RESPONSE_OK)) {
                            String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                            String CacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.GroupBuyClass);
                            if (!mHashNet.equals(CacheOperationHash)) {
                                fragment.showOption1View2(data.getData());
                                DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.GroupBuyClass, data.getData());
                            }

                        } else {
                            MToast.showToast(fragment.getActivity(), data.getMsg());
                        }
                    }
                });
            }
        }

        //获取供方发起二级分类
        public void getTenderCategoryAllList () {
            Type type = new TypeToken<List<PickSelectEntity>>() {
            }.getType();
            Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.GroupBuyClassTwo, type);
            if (null != obj) {
                List<PickSelectEntity> dataList = (List<PickSelectEntity>) obj;
                typeEntityList.clear();
                typeEntityList.addAll(dataList);
                fragment.showOption1View2(typeEntityList);
                return;
            }
            APIManager.getInstance().getCentralizedMiningAPI().getSecondCategory("0", "1").enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
                @Override
                public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                    if (data.getState().equals(APIManager.RESPONSE_OK)) {
                        String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                        String CacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.GroupBuyClassTwo);
                        if (!mHashNet.equals(CacheOperationHash)) {
                            typeEntityList.clear();
                            for (CommonPopEntity commonPopEntity : data.getData()) {
                                typeEntityList.add(new PickSelectEntity(commonPopEntity.getNo(), commonPopEntity.getTypeName()));
                            }
                            fragment.showOption1View2(typeEntityList);
                            DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.GroupBuyClassTwo, typeEntityList);
                        }
                    } else {
                        MToast.showToast(fragment.getActivity(), data.getMsg());
                    }
                }
            });
        }

        //二级分类
        public void getTenderGoodsCategoryAllList (String no,int index){
            Call<BaseEntity<List<CommonPopEntity>>> call = null;
            if (index == 1) { // 商品材料
                call = APIManager.getInstance().getCentralizedMiningAPI().getSecondCategory(no, "1");
            } else if (index == 2) { // 机械租赁
                call = APIManager.getInstance().getCentralizedMiningAPI().getSecondCategory(no, "2");
            } else if (index == 3) { // 设备租赁
                call = APIManager.getInstance().getCentralizedMiningAPI().getSecondCategory(no, "3");
            }
            if (call == null) {
                return;
            }
            call.enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
                @Override
                public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                    if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                        typeEntityList.clear();
                        for (CommonPopEntity commonPopEntity : data.getData()) {
                            typeEntityList.add(new PickSelectEntity(commonPopEntity.getNo(), commonPopEntity.getTypeName()));
                        }
                        fragment.showOption2View3(typeEntityList);
                    }
                }
            });
        }

        /**
         * 获取供方发起列表
         */
        public void getFactoryCentralizedList ( boolean loadMore, int page, String firstType){
            if (TextUtils.isEmpty(firstType) && fragment.getPosition() == 0 && page == 1) {
                Type type = new TypeToken<FactoryCentralizedListEntity<FactoryCentralizedItemEntity>>() {
                }.getType();
                Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheGroupBuySupplier + firstType, type);
                if (null != obj && !loadMore) {
                    FactoryCentralizedListEntity<FactoryCentralizedItemEntity> dataList = (FactoryCentralizedListEntity<FactoryCentralizedItemEntity>) obj;
                    fragment.showFactoryList(dataList.getList(), loadMore);
                    return;
                }
            }
            if (page != 1) {
                DialogHelper.showProgressDialog(fragment.getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
            }
            map = new HashMap();
            map.put("current", page);
            map.put("limit", 3);
            map.put("firstType", firstType);
            APIManager.getInstance().getCentralizedMiningAPI().getFactoryCentralizedList(map).enqueue(new ICallBack<BaseEntity<FactoryCentralizedListEntity<FactoryCentralizedItemEntity>>>() {
                @Override
                public void onSuccess(BaseEntity<FactoryCentralizedListEntity<FactoryCentralizedItemEntity>> data) {
                    DialogHelper.dismissProgressDialog();
                    if (data == null || data.getState() == null) {
                        return;
                    }
                    if (data.getState().equals(APIManager.RESPONSE_OK)) {
                        if (TextUtils.isEmpty(firstType) && fragment.getPosition() == 0 && page == 1) {
                            String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                            String CacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CacheGroupBuySupplier + firstType);
                            if (!mHashNet.equals(CacheOperationHash)) {
                                fragment.showFactoryList(data.getData().getList(), loadMore);
                                DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheGroupBuySupplier + firstType, data.getData());
                            }
                        } else {
                            fragment.showFactoryList(data.getData().getList(), loadMore);
                        }
                    } else {
                        MToast.showToast(fragment.getContext(), data.getMsg());
                    }
                }
            });
        }
    }
